<template>
  <div class="editor-container">
    <div class="editor-header">
      <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
      <div class="header-actions">
        <el-button
          type="primary"
          :loading="saving"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </div>
    
    <div class="editor-body">
      <div class="editor-meta">
        <el-input
          v-model="form.title"
          placeholder="请输入标题..."
          size="large"
          class="title-input"
        />
        
        <div class="meta-row">
          <el-select
            v-model="form.notebook_id"
            placeholder="选择笔记本"
            clearable
            style="width: 200px; margin-right: 12px;"
          >
            <el-option
              v-for="notebook in notebookStore.notebooks"
              :key="notebook.id"
              :label="notebook.name"
              :value="notebook.id"
            />
          </el-select>
          
          <el-select
            v-model="form.tag_ids"
            multiple
            placeholder="选择标签"
            style="width: 300px; margin-right: 12px;"
          >
            <el-option
              v-for="tag in tagStore.tags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
          
          <el-checkbox v-model="form.is_pinned">置顶</el-checkbox>
        </div>
      </div>
      
      <div class="editor-content">
        <div ref="editorRef" class="rich-editor"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useNoteStore } from '@/stores/note'
import { useNotebookStore } from '@/stores/notebook'
import { useTagStore } from '@/stores/tag'

const route = useRoute()
const router = useRouter()
const noteStore = useNoteStore()
const notebookStore = useNotebookStore()
const tagStore = useTagStore()

const editorRef = ref()
const saving = ref(false)
const editor = ref(null)

const form = reactive({
  title: '',
  content: '',
  notebook_id: null,
  tag_ids: [],
  is_pinned: false
})

const noteId = route.params.id

onMounted(async () => {
  // 加载笔记本和标签
  await Promise.all([
    notebookStore.fetchNotebooks(),
    tagStore.fetchTags()
  ])
  
  // 如果是编辑模式，加载笔记
  if (noteId) {
    const note = await noteStore.fetchNote(noteId)
    form.title = note.title
    form.content = note.content
    form.notebook_id = note.notebook_id
    form.tag_ids = note.tags.map(t => t.id)
    form.is_pinned = note.is_pinned
  }
  
  // 初始化编辑器（简化版，实际使用需要引入 wangeditor）
  initEditor()
})

onBeforeUnmount(() => {
  if (editor.value) {
    editor.value.destroy()
  }
})

function initEditor() {
  // 这里简化处理，实际需要正确初始化 wangeditor
  // 由于 wangeditor 需要复杂配置，这里提供一个基础的 textarea 替代方案
  const textarea = document.createElement('textarea')
  textarea.className = 'simple-editor'
  textarea.placeholder = '开始写作...'
  textarea.value = form.content
  textarea.addEventListener('input', (e) => {
    form.content = e.target.value
  })
  editorRef.value.appendChild(textarea)
}

async function handleSave() {
  if (!form.title.trim()) {
    ElMessage.warning('请输入标题')
    return
  }
  
  saving.value = true
  try {
    if (noteId) {
      await noteStore.modifyNote(noteId, form)
    } else {
      await noteStore.addNote(form)
    }
    goBack()
  } finally {
    saving.value = false
  }
}

function goBack() {
  router.push('/')
}
</script>

<style scoped>
.editor-container {
  max-width: 1000px;
  margin: 0 auto;
  background: white;
  border-radius: 8px;
  min-height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.editor-header {
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.editor-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
}

.editor-meta {
  margin-bottom: 24px;
}

.title-input {
  margin-bottom: 16px;
}

.title-input :deep(.el-input__inner) {
  font-size: 24px;
  font-weight: 600;
  border: none;
  padding: 0;
}

.meta-row {
  display: flex;
  align-items: center;
}

.editor-content {
  flex: 1;
  min-height: 400px;
}

.rich-editor {
  height: 100%;
}

.simple-editor {
  width: 100%;
  height: 500px;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 16px;
  line-height: 1.6;
  resize: vertical;
  font-family: inherit;
}

.simple-editor:focus {
  outline: none;
  border-color: #409eff;
}
</style>

